<?php
/**
 * RQCMS 1.0   A simple,personal,multi-site cms 
 *
 * @copyright  Copyright (c) 2010-2012 RQ204
 * @license    GNU General Public License 2.0
 * @t          http://t.qq.com/winslow
 */
 //版权相关设置
define('RQ_AppName','RQCMS');
define('RQ_VERSION','0.99');
define('RQ_RELEASE','20120701');
define('RQ_AUTHOR','RQ204');
define('RQ_WEBSITE','http://www.rqcms.com');
define('RQ_EMAIL','rq204@qq.com');

//核心参数
define('RQ_ROOT',dirname(__file__));
define('RQ_CORE',RQ_ROOT.'/core');
define('RQ_DATA',RQ_ROOT.'/data');
define('RQ_HOST',$_SERVER['HTTP_HOST']);
define('RQ_POST',$_SERVER['REQUEST_METHOD'] == 'GET' ? false : true);
define('RQ_HTTP',(isset($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'],'off')!=0) ? 'https://' : 'http://');
define('RQ_ISIE',strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')); 
foreach(array('REDIRECT_URL','HTTP_X_REWRITE_URL','REQUEST_URI','SCRIPT_NAME') as $rqfile)
{
	if(isset($_SERVER[$rqfile]))
	{	
		define('RQ_FILE',($_SERVER[$rqfile]=='/'||$_SERVER[$rqfile]=='/?')?'index.php':ltrim(strpos($_SERVER[$rqfile],'?')>1?substr($_SERVER[$rqfile],0,strpos($_SERVER[$rqfile],'?')):$_SERVER[$rqfile],'/'));break;
	}
}

//加载公共类和配置文件
include RQ_CORE.'/library/class.mysql.php';
include RQ_CORE.'/library/func.base.php';
include RQ_CORE.'/library/func.cache.php';
include RQ_CORE.'/library/func.data.php';
include RQ_DATA.'/config.php';

//处理部分服务器对重写的网址没有GET参数的解决办法,如kangle服务器
if(empty($_GET)&&strpos($_SERVER['REQUEST_URI'],'?')>1)
{
	foreach(explode('&',substr($_SERVER['REQUEST_URI'],strpos($_SERVER['REQUEST_URI'],'?')+1)) as $tget)
	{
		$gets=explode('=',$tget);
		$_GET[$gets[0]]=isset($gets[1])?$gets[1]:'';
	}
}
if(empty($_POST)&&isset($HTTP_RAW_POST_DATA)) $_POST=$HTTP_RAW_POST_DATA;

//错误提示设置和参数过滤
if(RQ_DEBUG) 
{
	error_reporting(E_ALL);
	set_error_handler("debug");
}
else error_reporting(0);
ob_start();
doStripslashes();
if(get_magic_quotes_runtime()) set_magic_quotes_runtime(false);

//数据库实例化
$DB=new DB_MySQL();
$DB->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE,0);

//读取缓存数据,加载插件
$Hosts = array();//站点数据,如果为多个,则需要判断是否存在的站点
$Files = array();//文件数组,需要寻找对应的文件并包含
$Plugins = array();//插件文件数组
$PluginsConfig=array();//插件的配置数据
$wdHooks = array();//插件函数数据
$Hosts = @include RQ_DATA.'/cache/hosts.php';//加载所有站点信息
$cates=array();//当前站点的分类数据
$var=array();//当前站点的变量数据,建议插件的缓存也加入

if($Hosts&&is_array($Hosts)&&isset($Hosts[RQ_HOST]))
{
	$host=$Hosts[RQ_HOST];//站点数组,包含
}
else if($Hosts&&is_array($Hosts)&&!isset($Hosts[RQ_HOST]))
{
	//如果使用了泛解析的，多级域名的处理
	foreach($Hosts as $hs)
	{	
		//$aliasname为除过根域名外的域名部分，如 xx.rq.cn 相对 rq.cn 多出来的 xx 即为该值
		$aliasname=substr(RQ_HOST,0,strlen(RQ_HOST)-strlen($hs['host']));
		if(substr(RQ_HOST,0-(strlen($hs['host'])))==$hs['host']&&substr($aliasname,-1)=='.')
		{
			$Hosts = @include RQ_DATA.'/cache/hosts.php';
			$host=$Hosts[$hs['host']];
			$aliasname=substr($aliasname,0,strlen($aliasname)-1);
			break;
		}
		else unset($aliasname);
	}
}
if(isset($host))
{
	$hostid=$host['hid'];//站点id
	$theme=$host['theme'];//站点模板
	$Files= @include RQ_DATA.'/cache/map_'.$host['host'].'.php';
	$cates=@include RQ_DATA.'/cache/cate_'.$host['host'].'.php';
	$var=@include RQ_DATA.'/cache/var_'.$host['host'].'.php';
	$Plugins = @include RQ_DATA.'/cache/plugins.php';
	if(!$cates) $cates=array();
	if(isset($Plugins)&&!empty($Plugins))
	{
		foreach($Plugins as $pluginHost=>$pluginNameValue)
		{
			if($host['host']==$pluginHost)
			{
				$Plugins=$Plugins[$pluginHost];
			}
		}
	}
}

//时区的设置
date_default_timezone_set('Asia/Shanghai');
$timestamp=time();

//IP地址和User-Agent
$onlineip=getIp();
$useragent=addslashesDeep($_SERVER['HTTP_USER_AGENT']);

//设置运行的文件
if(!$Files||!is_array($Files))
{
	$Files=array('file'=>array('install.php'=>'install.php'),'arg'=>array());
}
else //权限判定
{
	$username=$groupid=$uid=0;
	$sessionid=isset($_COOKIE['sessionid'])?$_COOKIE['sessionid']:'';
	if(isset($_GET['sessionid'])) $sessionid=$_GET['sessionid'];//在多站点切换时,使用这个来保持登陆状态
	if(!empty($sessionid)&&strlen($sessionid)==30)
	{
		$userinfo=$DB->fetch_first('Select * from '.DB_PREFIX."user where `sessionid`='$sessionid' and (`groupid`=4 or `hostid`='$hostid')");//创始人可以登陆每个站点,其他人受限
		if($userinfo)
		{
			$nowips=explode('.',$onlineip);
			$oldips=explode('.',$userinfo['loginip']);
			$diffip=array_diff_assoc($nowips,$oldips);
			if(count($diffip)<2&&!isset($diffip[2])&&$useragent==$userinfo['useragent'])//当最后一位不同时认为是同一地点
			{
				$uid=$userinfo['uid'];
				$username=$userinfo['username'];
				$groupid=$userinfo['groupid'];//0是游客,1注册会员,2编辑,3管理员,4创始人
			}
			if(!isset($_COOKIE['sessionid'])||$_COOKIE['sessionid']!=$sessionid)
			{	
				if(isset($_COOKIE['sessionid'])&&$_COOKIE['sessionid']!=$sessionid) 
				{
					setcookie('sessionid','');
					if(!RQ_ISIE) setcookie('sessionid','',-1,'/','.'.$host['host']);//使用泛域名解析后，需要删除.rq.cn这样的cookie的域
					message('站点切换成功','admin.php?sessionid='.$sessionid);
				}
				else 
					setcookie('sessionid',$sessionid);
			}
		}
	}
}
//先选择cms,再选模块，创建表格
//文章
function getsoftlinks($a)
{
	//"{}market://details?id=jp.co.android.viewer.kare_first_loveJP000&referrer=utm_source%3Dappbrain%26utm_medium%3Dmobileweb%26utm_campaign%3Dreferral {/dede:link}";
	$b=strpos($a,'}');
	if($b>0)
	{
		$c=strpos($a,'{',$b);
		if($c>0)
		{
			$d=substr($a,$b+1,$c-$b-1);
			return $d;
		}
	}
	return '';
}

$hostid=1;
$lastid=isset($_GET['id'])?intval($_GET['id']):0;
/* if($lastid==0) 
{
	$DB->query('TRUNCATE `'.DB_PREFIX.'article`');
	//$DB->query('ALTER TABLE `'.DB_PREFIX."article` ADD COLUMN `litpic` VARCHAR(200) NOT NULL DEFAULT '' AFTER `ban`");
	//$DB->query('ALTER TABLE `'.DB_PREFIX."article` ADD COLUMN `writer` VARCHAR(200) NOT NULL DEFAULT '' AFTER `ban`");
		
	$DB->query('TRUNCATE `'.DB_PREFIX.'content`');
	/* $DB->query('ALTER TABLE `'.DB_PREFIX.'content` ADD COLUMN `language` VARCHAR(10) NOT NULL DEFAULT ""');
	$DB->query('ALTER TABLE `'.DB_PREFIX."content` ADD COLUMN `softsize` VARCHAR(10) NOT NULL DEFAULT ''");
	$DB->query('ALTER TABLE `'.DB_PREFIX."content` ADD COLUMN `softlinks` VARCHAR(200) NOT NULL DEFAULT ''");
	$DB->query ('ALTER TABLE `'.DB_PREFIX."content` ADD COLUMN `softsize` VARCHAR(10) NOT NULL DEFAULT ''");
	
	$DB->query('TRUNCATE `'.DB_PREFIX.'tag`');
}
$query=$DB->query('select * from dede_archives where id>'.$lastid.' order by id asc limit 500');
$num=$DB->fetch_row($query); */

//分类的处理
$DB->query('TRUNCATE `'.DB_PREFIX.'category`');
$query=$DB->query('select * from dede_arctype');
$catearr=array();
while($data=$DB->fetch_array($query))
{
	//if($data['reid']==0) continue;
	$cate['oid']=$data['id'];
	$cate['hostid']=$hostid;
	$cate['name']=$data['typename'];
	$cate['url']=trim($data['typedir'],'/');
	$cate['pid']=$data['topid'];
	$cate['style']='';
	$cate['keywords']=$data['keywords'];
	$cate['description']=$data['description'];
	$cate['visible']=1;
	$cate['displayorder']=0;

	$sql=getInsertSql($cate,'category');
	$DB->query($sql);
	$cid=$DB->insert_id();
	$catearr[$cid]=$data['id'];
	/* CREATE TABLE `rqcms_category` (


	`url` CHAR(60) NOT NULL DEFAULT '' COMMENT '栏目友好网址',
	`pid` SMALLINT(4) NOT NULL DEFAULT '0' COMMENT '父级栏目id',
	`style` VARCHAR(20) NOT NULL COMMENT '栏目模板风格',
	`keywords` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '栏目关键字',
	`description` VARCHAR(300) NOT NULL DEFAULT '' COMMENT '栏目描述',
	`visible` TINYINT(1) NOT NULL DEFAULT '1' COMMENT '是否可见',
	`displayorder` SMALLINT(5) NOT NULL DEFAULT '0' COMMENT '显示次序', */
}
foreach($catearr as $c=>$oid)
{
	//$sql='update '.DB_PREFIX."article set cateid=$c+100 where cateid=$oid and cateid<100";
	//$DB->query($sql);
	echo $sql.';';
}

exit('ok');
/* 
`id` SMALLINT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
	`reid` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0',
	`topid` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0',
	`sortrank` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '50',
	`typename` CHAR(30) NOT NULL DEFAULT '',
	`typedir` CHAR(60) NOT NULL DEFAULT '',
	`isdefault` SMALLINT(6) NOT NULL DEFAULT '0',
	`defaultname` CHAR(15) NOT NULL DEFAULT 'index.html',
	`issend` SMALLINT(6) NOT NULL DEFAULT '0',
	`channeltype` SMALLINT(6) NULL DEFAULT '1',
	`maxpage` SMALLINT(6) NOT NULL DEFAULT '-1',
	`ispart` SMALLINT(6) NOT NULL DEFAULT '0',
	`corank` SMALLINT(6) NOT NULL DEFAULT '0',
	`tempindex` CHAR(50) NOT NULL DEFAULT '',
	`templist` CHAR(50) NOT NULL DEFAULT '',
	`temparticle` CHAR(50) NOT NULL DEFAULT '',
	`namerule` CHAR(50) NOT NULL DEFAULT '',
	`namerule2` CHAR(50) NOT NULL DEFAULT '',
	`modname` CHAR(20) NOT NULL DEFAULT '',
	`description` CHAR(150) NOT NULL DEFAULT '',
	`keywords` VARCHAR(60) NOT NULL DEFAULT '',
	`seotitle` VARCHAR(80) NOT NULL DEFAULT '',
	`moresite` TINYINT(1) UNSIGNED NOT NULL DEFAULT '0',
	`sitepath` CHAR(60) NOT NULL DEFAULT '',
	`siteurl` CHAR(50) NOT NULL DEFAULT '',
	`ishidden` SMALLINT(6) NOT NULL DEFAULT '0',
	`cross` TINYINT(1) NOT NULL DEFAULT '0',
	`crossid` TEXT NULL,
	`content` TEXT NULL,
	`smalltypes` TEXT NULL,
	PRIMARY KEY (`id`),
	INDEX `reid` (`reid`, `isdefault`, `channeltype`, `ispart`, `corank`, `topid`, `ishidden`),
	INDEX `sortrank` (`sortrank`),
	INDEX `namerule` (`namerule`),
	INDEX `namerule2` (`namerule2`),
	INDEX `topid` (`topid`),
	INDEX `typename` (`typename`),
	INDEX `typedir` (`typedir`),
	INDEX `reid_2` (`reid`),
	INDEX `ispart` (`ispart`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM
ROW_FORMAT=DEFAULT
AUTO_INCREMENT=37 */

$num=0;
if($num>0)
{
	$oldandnew=array();
	//pubdate  senddate 发布时间和录入时间
	while($data=$DB->fetch_array($query))
	{
		$article['oid']=$data['id'];
		$article['hostid']=$hostid;
		$article['cateid']=$data['typeid'];
		$article['userid']='1';
		$article['title']=$data['title'];
		$article['keywords']=$data['keywords'];
		$article['tag']='';
		$article['url']=$data['filename'];
		$article['thumb']='';//
		$article['source']='';
		$article['excerpt']=$data['description'];
		$article['dateline']=$data['pubdate'];
		$article['modified']=$data['lastupdate'];
		$article['views']=$data['click'];
		$article['comments']='';
		$article['attachments']='';
		$article['closed']=0;
		$article['visible']=1;
		$article['stick']=0;
		$article['password']='';
		$article['ban']=0;

		//add
		$article['litpic']=$data['litpic'];
		$article['writer']=$data['writer'];
		
		$lastid=$data['id'];
		$sql=getInsertSql($article,'article');
		$DB->query($sql);
		
		$aid=$DB->insert_id();
		
		$oldandnew[$lastid]=$aid;
	}
	
	$oids=implode(',', array_keys($oldandnew));
	$query=$DB->query("Select * from dede_addonsoft where aid in ($oids)");
	while($data=$DB->fetch_array($query))
	{
		$content['articleid']=$oldandnew[$data['aid']];
		$content['language']=$data['language'];
		$content['softsize']=$data['softsize'];
		$content['content']=$data['introduce'];
		$content['softlinks']=getsoftlinks($data['softlinks']);
		
		$sql=getInsertSql($content,'content');
		$DB->query($sql);
	}
	
	$idandtag=array();
	$query=$DB->query("Select * from dede_taglist where aid in ($oids)");
	$no=array('+','-','++','--','$','$$','$$$','*','.','..','...','.','/','//','034;','');//len==2
	while($data=$DB->fetch_array($query))
	{
		$tdata=$data['tag'];
		if(!in_array($tdata,$no)) $idandtag[$oldandnew[$data['aid']]][]=$tdata;
	}
	$sql=getTagSql($idandtag,'tag',$hostid);
	$DB->query($sql);
	//更新article

	foreach($idandtag as $aid=>$tags)
	{
		$tagstr=implode(',',$tags);
		$DB->query('update '.DB_PREFIX."article set tag='$tagstr' where aid=$aid");
	}

	$url='<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta HTTP-EQUIV="REFRESH" content="1;URL=anwang.php?id='.$lastid.'"></head><body>跳转中<body></html>';
	exit($url);
}


function getInsertSql($arr,$table)
{
	$sql='Insert into `'.DB_PREFIX.$table."` set ";
	foreach($arr as $t=>$v)
	{
		$sql.="`$t`='".addslashes($v)."',";
	}
	$sql=trim($sql,',');
	return $sql;
}

function getTagSql($idandtag,$table,$hostid)
{
	$sql='Insert into `'.DB_PREFIX.$table."` (`tag`,`articleid`,hostid) values ";
	foreach($idandtag as $id=>$tags)
	{
		foreach($tags as $tag)
		{
			$sql.="('$tag','$id','$hostid'),";
		}
	}
	$sql=trim($sql,',');
	return $sql;
}
